<template>
  <div class="wrapper">
    <!-- 卡片组件 -->
    <card _Title="我的订单" :_Size="16" :_Tabs="changeWay" @_Change="change" v-if="!homePage"></card>
    <card _Title="我的订单" :_Size="16" :_Tabs="changeWay" @_Change="change" _More="全部订单" _Src="/home/MyOrder" v-else>
    </card>
    <!-- 搜索 筛选 -->
    <div class="mb_24 box" v-if="current != null">
      <div class="global_float_right">
        <!-- v-model="params.keywords" -->
        <Input class="width_300" search enter-button placeholder="请输入订单号搜索" @on-search="GetOrderList" />
      </div>
    </div>
    <!-- 订单列表 -->
    <empty v-if="list.length === 0" />
    <!-- 商品部分 -->
    <div class="only-goods-list flex-j-sb" v-else>
      <div class="only-goods-list-item" v-for="(item, index) in list" :key="index" @click.stop="openModel(item)">
        <div class="goods-desc1" v-if="item.desired">订单号：{{ item.orderNum }}</div>

        <div class="goods-price">
          <span class="price" v-if="roles == 'user'">{{ item.price | unitPrice("￥") }}</span>
          <span class="price" v-else>{{ item.allotPrice | unitPrice("￥") }}</span>
          <span class="state"> {{(typeList.find(x => x.value == item.state) || {}).label || '未知状态'}}</span>
        </div>
        <div>
          <div class="goods-name wes-2">{{ item.title }}</div>
          <div class="goods-desc">需求类型：{{ getType(item.desired ? item.desired.type : item.type) }}</div>
          <div class="goods-desc">发布时间：{{ item.createTime }}</div>
          <div class="goods-desc">需求描述：{{ item.desired ? item.desired.content : item.content }}</div>
          <!-- <div class="goods-desc">发布人：{{ item.user.nickName }}</div> -->
        </div>
        <!-- 查看 -->
        <div class="white-shadow">
          <div class="search">去查看</div>
        </div>
      </div>
    </div>
    <div class="goodsButton" v-if="Page.total >= 16">
      <Page :total="Page.total" @on-change="PageChange" /> <!-- show-sizer -->
    </div>
    <Modal v-model="modal" :title="title" width="70%">
      <div style="margin-bottom : 10px;">
        <Steps :current="getCurrent(formValidate)" size="small" :key="filteredTypeList.length">
          <Step v-for="item in filteredTypeList" :key="item.value" :content="item.label"></Step>
        </Steps>
      </div>
      <Row>
        <Col span="12" v-if="formValidate.state == 15">
        <Form ref="formValidates" :model="formValidate" :rules="ruleValidate" :label-width="100">
          <FormItem label="需求类型" prop="type">
            <Select v-model="clickType" :disabled="formValidate.state != 15" @on-change="clickTypeFun" multiple
              placeholder="请选择需求类型">
              <Option v-for="(item, i) in type" :value="item.value" :key="i">{{ item.label }}</Option>
            </Select>
          </FormItem>
          <FormItem label="需求标题" prop="title">
            <Input v-model="formValidate.title" :disabled="formValidate.state != 15" placeholder="请输入需求标题"></Input>
          </FormItem>
          <FormItem label="需求起止时间" prop="startTime">
            <DatePicker type="datetimerange" :options="options" :disabled="formValidate.state != 15" v-model="date"
              @on-change="handleClickDate" placeholder="开始时间-结束时间" style="width: 240px" />
          </FormItem>
          <!-- <FormItem label="佣金金额" prop="price">
            <Input v-model="formValidate.price" :disabled="formValidate.state != 15" placeholder="请输入佣金金额"></Input>
          </FormItem> -->
          <FormItem label="附件上传" prop="file">
            <FileUpload @input="FileUploadInput" :value="formValidate.file" />
          </FormItem>
          <FormItem label="需求描述" prop="content">
            <Input v-model="formValidate.content" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="请输入需求描述" />
            <div style="color: #ff5343;">
              提示：可补充上传文件和需求描述
            </div>
          </FormItem>
          <FormItem label="备注">
            <Input v-model="formValidate.remark" :disabled="formValidate.state != 15" type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }" placeholder="请输入备注"></Input>
          </FormItem>
          <FormItem label="其他需求" prop="other">
            <Input v-model="formValidate.other" :disabled="formValidate.state != 15" type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }" placeholder="请输入其他需求"></Input>
          </FormItem>
        </Form>
        </Col>
        <Col span="12" v-else>
        <Form :label-width="100">
          <FormItem label="需求类型:">
            <div>{{ getType(formValidate.type) }}</div>
          </FormItem>
          <FormItem label="需求标题:">
            {{ formValidate.title }}
          </FormItem>
          <FormItem label="需求起止时间:">
            {{ formValidate.startTime }} - {{ formValidate.endTime }}
          </FormItem>
          <FormItem label="需求附件:" v-if="formValidate.file != null">
            <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear"
              tag="ul">
              <li class="el-upload-list__item ele-upload-list__item-content" style="cursor: pointer;"
                v-for="file in getFileList(formValidate.file)" :key="file" @click="downloadLocalFile(file)">
                <div>
                  <Icon type="md-list-box" /> {{ getFileName(file) }}
                </div>
              </li>
            </transition-group>
          </FormItem>
          <FormItem label="反馈文件："
            v-if="roles == 'user' && formValidate.file != null && formValidate.order && formValidate.order.state >= 60">
            <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear"
              tag="ul">
              <li class="el-upload-list__item ele-upload-list__item-content" style="cursor: pointer;"
                v-for="file in getFileList(feedbackFrom.feedbackFile)" :key="file" @click="downloadLocalFile(file)">
                <div>
                  <Icon type="md-list-box" /> {{ getFileName(file) }}
                </div>
              </li>
            </transition-group>
          </FormItem>
          <FormItem label="金额:" v-if="formValidate.order">
            {{ roles == 'user' ? formValidate.price : formValidate.order.allotPrice }}
          </FormItem>
          <FormItem label="需求描述:">
            {{ formValidate.content }}
          </FormItem>
          <FormItem label="备注:">
            {{ formValidate.remark }}
          </FormItem>
          <FormItem label="其他需求:">
            {{ formValidate.other }}
          </FormItem>
        </Form>
        </Col>
        <Col span="1">
        </Col>
        <Col span="11" style="max-height: 550px;overflow: auto;">
        <Timeline>
          <!-- :class="getClass(item.value)" -->
          <TimelineItem v-for="(item, i) in TimelineArr" :key="i">
            <p class="time">{{ item.createTime }}</p>
            <div class="content" v-if="item.type == 5">
              <p>{{ item.content.name }}</p>
              <p>需求内容：{{ item.content.content }}</p>
              <p>需求价格：{{ item.content.price }}元</p>
              <!-- <p @click="downLoadFile(item.content.file)" style="cursor: pointer;">
                <Icon type="ios-document" />
                查看文件
              </p> -->
            </div>
            <p class="content" v-else>{{ item.content }}</p>
          </TimelineItem>
        </Timeline>
        </Col>
      </Row>
      <div slot="footer">
        <Button @click="cancel">取消</Button>
        <Button style="background-color: #ff5343;color: #fff;" v-if="formValidate.state == 15"
          @click="handleSubmit('11')">重新提交</Button>
        <Button v-if="roles == 'user' && formValidate.order && formValidate.order.state == 30"
          style="background-color: #ff5343;color: #fff;" @click="QRCode = true; paymentTypeFun()">付款</Button>
        <Button
          v-if="roles == 'user' && formValidate.order && formValidate.order.state > 30 && formValidate.order.state < 70"
          style="background-color: #ff5343;color: #fff;" @click="modal = false, SupplementModal = true">补充需求</Button>
        <Button v-if="roles == 'writers' && formValidate.order && formValidate.order.state == 50"
          style="background-color: #ff5343;color: #fff;" @click="upLoadBackFile = true;">上传反馈文件</Button>
        <Button v-if="roles == 'writers' && formValidate.order && formValidate.order.state == 65"
          style="background-color: #ff5343;color: #fff;" @click="upLoadBackFile = true;">重新上传反馈文件</Button>
        <Button v-if="roles == 'user' && formValidate.order && formValidate.order.state == 60"
          style="background-color: #ff5343;color: #fff;" @click="upLoadBackFile = true;">查看写手反馈文件</Button>
        <!-- <Button v-if="roles == 'user' && formValidate.order && formValidate.order.state == 70"
          style="background-color: #ff5343;color: #fff;" @click="QRCode = true">结尾款</Button> -->
        <!-- && formValidate.order && formValidate.order.state == 30 -->
        <Button v-if="roles == 'user' && formValidate.order && formValidate.order.state == 70"
          style="background-color: #ff5343;color: #fff;" @click="evaluation = true">去评价</Button>
        <Button v-if="roles == 'user' && formValidate.order && formValidate.order.state == 70"
          style="background-color: #ff5343;color: #fff;" @click="GetorderAfterSale">去售后</Button>
        <Button
          v-if="roles == 'user' && formValidate.order && formValidate.order.state >= 50 && formValidate.order.state < 70"
          style="background-color: #ff5343;color: #fff;" @click="GetorderAfterSale">申请退款</Button>

        <Button v-if="roles == 'user' && formValidate.order && formValidate.order.state == 85"
          style="background-color: #ff5343;color: #fff;" @click="toCompleted">已完成</Button>
      </div>
    </Modal>
    <Modal v-model="QRCode" width="400px" class-name="ivu-modal-wrap1">
      <!-- <Form ref="evaluationModel" :model="evaluationModel" :label-width="100">
        <FormItem label="付款类型" v-if="formValidate.order && formValidate.order.state != 70">
          <Select v-model="paymentType" style="width: 220px;" @on-change="paymentTypeFun" placeholder="请选择需求类型">
            <Option value="0">全款</Option>
            <Option value="1">定金</Option>
          </Select>
        </FormItem>
      </Form> -->
      <div class="QRCode">
        <img class="QRImg" src="" alt="" srcset="">
        <!-- <p v-if="formValidate.order && formValidate.order.state != 70" >支付{{ payMoney }}元</p>   v-else-->
        <p>支付{{ formValidate.price }}元</p>
      </div>
      <div slot="footer" class="QRflex">
        <Button @click="cancel">取消</Button>
        <Button style="background-color: #ff5343;color: #fff;" @click="payment">去付款</Button>
      </div>
    </Modal>
    <Modal v-model="evaluation" title="评价" width="60%">
      <Form ref="evaluationModel" :model="evaluationModel" :label-width="100">
        <FormItem label="图片上传">
          <FileUpload @input="FileUploadInput2" :fileType="['png', 'jpg', 'jpeg']" :value="evaluationModel.image">
          </FileUpload>
        </FormItem>
        <FormItem label="评价内容">
          <Input v-model="evaluationModel.content" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="请输入评价内容"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="cancel">取消</Button>
        <Button style="background-color: #ff5343;color: #fff;" @click="evaluationFun">确定</Button>
      </div>
    </Modal>
    <Modal v-model="afterSales" title="申请售后" width="60%">
      <Form :label-width="100">
        <FormItem label="评价星级">
          <Rate v-model="evaluationModel.star" :max="5" :allow-half="true"></Rate>
        </FormItem>
        <FormItem label="售后原因">
          <Input v-model="afterSalesContent" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="请输入售后原因"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="cancel">取消</Button>
        <Button style="background-color: #ff5343;color: #fff;" @click="GetorderAfterSale">确定</Button>
      </div>
    </Modal>
    <Modal v-model="upLoadBackFile" :title="roles == 'user' ? '查看写手反馈' : '反馈提交'" width="60%">
      <Form ref="feedbackFrom" :model="feedbackFrom" :label-width="85">
        <FormItem label="反馈文件上传" prop="feedbackFile" v-if="roles == 'writers'">
          <FileUpload @input="FileUploadInput1" :value="feedbackFrom.feedbackFile"></FileUpload>
        </FormItem>
        <FormItem label="反馈文件下载" prop="feedbackFile" v-if="roles == 'user'">
          <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear"
            tag="ul">
            <li class="el-upload-list__item ele-upload-list__item-content" style="cursor: pointer;"
              v-for="file in getFileList(feedbackFrom.feedbackFile)" :key="file" @click="downloadLocalFile(file)">
              <div>
                <Icon type="md-list-box" /> {{ getFileName(file) }}
              </div>
            </li>
          </transition-group>
        </FormItem>
        <FormItem label="反馈文字">
          <Input v-model="feedbackFrom.feedbackContent" type="textarea" :disabled="roles == 'user'"
            :autosize="{ minRows: 2, maxRows: 5 }" placeholder="请输入反馈文字"></Input>
        </FormItem>
        <!-- <FormItem label="客户反馈">
          <Input v-model="feedbackFrom.remark" :disabled="roles == 'writers'" type="textarea"
            :autosize="{ minRows: 2, maxRows: 5 }" placeholder="请输入客户反馈"></Input>
        </FormItem> -->
      </Form>
      <div slot="footer">
        <Button @click="upLoadBackFile = false">取消</Button>
        <Button style="background-color: #ff5343;color: #fff;" v-if="roles == 'writers'" @click="handleTest">确定</Button>
        <Button v-if="roles == 'user'" style="background-color: #ff5343;color: #fff;"
          @click="ToReview('70')">审核通过</Button>
        <Button v-if="roles == 'user'" style="background-color: #ff5343;color: #fff;"
          @click="ToReview('65')">审核不通过</Button>
      </div>
    </Modal>
    <Modal v-model="SupplementModal" title="补充需求提交" width="60%" @on-close="cancel">
      <Form ref="formSupplement" :model="formValidate" :rules="ruleValidate" :label-width="100">
        <Row>
          <Col span="15">
          <FormItem label="需求类型" prop="type">
            <Select v-model="clickType" @on-change="clickTypeFun" multiple placeholder="请选择需求类型">
              <Option v-for="(item, i) in type" :value="item.value" :key="i">{{ item.label }}</Option>
            </Select>
          </FormItem>
          <FormItem label="需求标题" prop="title">
            <Input v-model="formValidate.title" placeholder="请输入需求标题"></Input>
          </FormItem>
          <FormItem label="需求描述" prop="content">
            <Input v-model="formValidate.content" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="请输入需求描述"></Input>
          </FormItem>
          <FormItem label="附件上传" prop="file">
            <FileUpload @input="FileUploadInput" :value="formValidate.file"></FileUpload>
          </FormItem>
          <FormItem label="需求起止时间" prop="startTime">
            <DatePicker type="datetimerange" :options="options" v-model="date" @on-change="handleClickDate"
              placeholder="开始时间-结束时间" style="width: 240px" />
          </FormItem>
          <FormItem label="备注">
            <Input v-model="formValidate.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="请输入备注"></Input>
          </FormItem>
          <FormItem label="其他需求">
            <Input v-model="formValidate.other" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="请输入其他需求"></Input>
          </FormItem>
          </Col>
        </Row>
        <!-- <Checkbox v-model="single">协议勾选有客户提供二次点击后跳转内容</Checkbox> -->
      </Form>
      <div slot="footer">
        <Button @click="cancel">取消</Button>
        <Button style="background-color: #ff5343;color: #fff;" @click="handleSubmit1('formSupplement')">确认</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  saveDesired, supplementDesired, getOrderList, getDesiredById, getDesiredInfo, getOrderTypeList,
  getOrderListByUserId, saveOrderApportion, getOrderApportionByUserId,
  updateDesired, auditOrderFeedback, saveEvaluate, orderAfterSale,
  writerDesiredList, getOrderRecords, payOrder, completeOrder, getMyDesiredList
} from "@/api/writer/index.js";
import storage from "@/plugins/storage";
import { Input } from 'view-design';
export default {
  name: "MyOrder",
  props: {
    homePage: {
      // 判断是否个人中心首页展示内容
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      changeWay: [],//label
      list: [],// 订单列表
      roleLabelsMap: {
        user: [
          { name: "全部", value: '-1' },
          { name: "我的需求", value: null },
          { name: "待支付", value: '30' },
          { name: "待分配", value: '40' },
          { name: "进行中", value: '50' },
          { name: "待验收", value: '60' },
          // { name: "已验收", value: '70' },
          // { name: "待评价", value: '80' },
          { name: "已完成", value: '100' },
          { name: "售后", value: '90' }
        ],
        writers: [
          { name: "全部", value: '-1' },
          { name: "进行中", value: '50' },
          { name: "待验收", value: '60' },
          // { name: "已验收", value: '70' },
          // { name: "待评价", value: '80' },
          { name: "已完成", value: '100' },
          { name: "售后", value: '90' }
        ],
      },
      TimelineArr: [],
      roles: "", // 角色
      typeList: [
        {
          label: "待分配",
          value: 0,
        },
        {
          label: "客服接单",
          value: 10,
        },
        {
          label: "重新审核",
          value: 11,
        },
        {
          label: "审核驳回",
          value: 15,
        },
        {
          label: "审核通过",
          value: 20,
        },
        {
          label: "待付款",
          value: 30,
        },
        {
          label: "待分配",
          value: 40,
        },
        {
          label: "进行中",
          value: 50,
        },
        {
          label: "待验收",
          value: 60,
        },
        {
          label: "用户驳回",
          value: 65,
        },
        {
          label: "已完成",
          value: 70,
        },
        {
          label: "待评价",
          value: 80,
        },
        {
          label: "已评价",
          value: 85,
        },
        {
          label: "售后订单",
          value: 90,
        },
        {
          label: "已退款",
          value: 99,
        },
      ],// 订单状态
      typeList1: [
        {
          label: "发布中",
          range: [0, 0]
        },
        {
          label: "客服接单",
          range: [10, 10]
        },
        {
          label: "客服审核",
          range: [15, 20]
        },
        {
          label: "待付款",
          range: [30, 30]
        },
        {
          label: "分配写手",
          range: [40, 40]
        },
        {
          label: "进行中",
          range: [50, 50]
        },
        {
          label: "待验收",
          range: [60, 65]
        },
        {
          label: "已完成",
          range: [70, 85]
        },
        {
          label: "去售后",
          range: [90, 90]
        },
      ],//主流程
      Page: {
        total: 0,
        pageNum: 1,
        pageSize: 16,
      },//分页
      baseUrl: BASE.API_DEV.buyer,
      current: "-1",
      modal: false,//需求弹窗
      modal1: false,//需求弹窗
      QRCode: false,//付款弹窗
      title: "新增需求",
      // labels: [],
      // single: false,
      formValidate: {
        type: null,
        title: '',
        content: '',
        file: [],
        price: null,
        remark: '',
        other: '',
        startTime: '',
        endTime: '',
      },
      feedbackFrom: {
        feedbackContent: '',
        feedbackFile: [],
        remark: ''
      },
      clickType: [],
      date: [],//日期
      defaultList: [],//附件列表
      feedbackList: [],//反馈文件列表
      type: [],//需求类型
      ruleValidate: {
        type: [
          { required: true, message: '请选择需求类型', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入需求标题', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入需求描述', trigger: 'blur' }
        ],
        file: [
          { required: true, message: '请选择附件上传', trigger: 'change' }
        ],
        // feedbackFile: [
        //   { required: true, message: '请选择附件上传', trigger: 'change' }
        // ],
        price: [
          { required: true, message: '请输入佣金金额', trigger: 'blur' },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入整数或两位小数',
            trigger: 'change'
          }
        ],
        startTime: [
          { required: true, message: '请选择日期', trigger: ['change', 'blur'] }
        ],
      },
      loading: false,
      evaluation: false,
      evaluationModel: {
        image: null,
        // star: 0,
        content: '',
        clickType: ''
      },
      paymentType: '0',//付款类型
      afterSales: false,//售后
      afterSalesContent: '',//售后原因
      modalRejectShow: false,
      SupplementModal: false,//补充需求弹框
      payMoney: '',//支付金额
      upLoadBackFile: false,//反馈文件上传
      options: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      },
      remark: '',//备注
    };
  },
  computed: {
    // shouldShowFormItem() {
    //   return this.title === '基础详情' && (this.formValidate.order || !this.formValidate.order);
    // },
    filteredTypeList() {
      let tempTypeList = this.typeList1;
      // if (this.formValidate.payRatio !== 100) {
      //   tempTypeList = tempTypeList.map(item => {
      //     if (item.label === '已验收') {
      //       return { ...item, label: `${item.label}（支付尾款）` };
      //     }
      //     return item;
      //   });
      // }
      if (this.formValidate.order && this.formValidate.order.state !== 90) {
        tempTypeList = tempTypeList.filter(item => item.label !== '去售后');
      }
      return tempTypeList;
    },
    selectedState: {
      get() {
        return this.formValidate.order ? this.formValidate.order.state : this.formValidate.state;
      },
      set(newValue) {
        if (this.formValidate.order) {
          this.formValidate.order.state = newValue;
        } else {
          this.formValidate.state = newValue;
        }
      }
    },
    isUserRole() {
      return this.roles === 'user';
    },
    isWriterRole() {
      return this.roles === 'writers';
    },
    isFileUploadDisabled() {
      return this.formValidate.state !== '5' && (!this.formValidate.order || this.formValidate.order.state !== 30);
    },
    isInputDisabled() {
      return this.formValidate.state !== '5' && (!this.formValidate.order || this.formValidate.order.state !== 30);
    },
    showInputTip() {
      return this.roles === 'user' && this.formValidate.order && this.formValidate.order.state === 30;
    }
  },
  mounted() {
    if (storage.getItem("roles")) {
      this.roles = storage.getItem("roles")
    }
    this.changeWay = this.roleLabelsMap[this.roles];
    this.GetOrderList()
    this.GetOrderTypeList()
  },
  methods: {
    //付款类型切换
    paymentTypeFun() {
      if (this.paymentType == '0') {
        this.payMoney = this.formValidate.price
      } else if (this.paymentType == '1') {
        const passFormPrice = parseFloat(this.formValidate.price);
        const payRatio = parseFloat(this.formValidate.payRatio);
        this.payMoney = (passFormPrice * (payRatio / 100)).toFixed(2);
      }
    },
    // 筛选出当前分类下的商品
    change(val) {
      console.log(val, "val");
      this.current = val;

      if (val) {
        this.GetOrderList()
      } else {
        this.GetMyDesiredList()
      }
    },
    handleSubmit(state) {
      // this.$refs['formValidates'].validate((valid) => {
      //   if (valid) {
      this.formValidate.file = this.defaultList.map(x => x.url).join(',')
      console.log(this.$refs['formValidates'], "this.$refs['formValidates']");


      saveDesired({
        ...this.formValidate,
        state: state == 11 ? '11' : this.formValidate.state,
      }).then(res => {
        console.log(res, "保存需求订单");
        if (res.code == 200) {
          this.$Message.success('保存成功!');
          this.modal = false;
          this.GetMyDesiredList()
        }
      })
      //   } else {
      //     this.$Message.error('请填写完整信息!');
      //   }
      // })
    },
    handleSubmit1(name) {
      // this.$refs[name].validate((valid) => {
      //   if (valid) {
      this.formValidate.file = this.defaultList.map(x => x.url).join(',')
      console.log(this.$refs['formValidates'], "this.$refs['formValidates']");
      supplementDesired({
        ...this.formValidate,
        id: 0,
        desiredId: this.formValidate.id,
      }).then(res => {
        console.log(res, "保存需求订单");
        if (res.code == 200) {
          this.$Message.success('保存成功!');
          this.SupplementModal = false;
        }
      })
      //   } else {
      //     this.$Message.error('请填写完整信息!');
      //   }
      // })
    },
    handleTest() {
      if (this.feedbackList.length == 0) {
        this.$Message.error('请上传反馈文件!');
        return
      }
      this.feedbackFrom.feedbackFile = this.feedbackList.map(x => x.url).join(',')
      console.log(this.feedbackFrom, this.feedbackList);
      // state:60,
      saveOrderApportion({ ...this.feedbackFrom, desiredId: this.formValidate.id, orderId: this.formValidate.order.id }).then(res => {
        console.log(res, "保存需求订单");
        if (res.code == 200) {
          this.$Message.success('保存成功!');
          this.modal = false;
          this.upLoadBackFile = false;
          // this.single = false
          setTimeout(() => {
            this.$refs.feedbackFrom.resetFields();
          }, 1000);
        }
      })
    },
    cancel() {
      this.modal = false;
      // this.single = false
      this.afterSales = false
      this.evaluation = false
      this.QRCode = false
      this.modalRejectShow = false
      this.SupplementModal = false
      this.upLoadBackFile = false

    },
    openModel(item) {
      // console.log(item);
      // console.log(item.desired.id);
      let id = this.current ? item.desired.id : item.id
      this.GetOrderTypeList()
      this.GetOrderRecords(id)

      if (this.roles == 'user') {
        this.GetDesiredById(id)
      } else {
        this.GetDesiredInfo(id)
      }
    },
    reset() {
      this.date = [];
      this.formValidate = {
        type: null,
        title: '',
        content: '',
        file: [],
        price: null,
        remark: '',
        other: '',
        startTime: null,
        endTime: null,
      }
      this.clickType = [];
      this.feedbackFrom = {
        feedbackContent: '',
        feedbackFile: [],
        remark: ''
      }
    },
    //获取需求列表
    GetOrderList(val) {
      const params = {
        pageNum: this.Page.pageNum,
        pageSize: this.Page.pageSize,
        state: Number(this.current),
        orderNum: val,
        // identity: this.roles == 'user' ? '0' : '1',
      }
      if (this.roles == 'user') {
        getOrderList(params).then((res) => {
          if (res.code == 200) {
            this.list = res.data.records;
            this.Page.total = res.data.total
          }
        });
      } else {
        getOrderListByUserId({ ...params, type: 20 }).then((res) => {
          if (res.code == 200) {
            this.list = res.data.records;
            console.log(this.list, 'this.list');

            this.Page.total = res.data.total
          }
        });
      }

    },
    //获取我的需求
    GetMyDesiredList() {
      const params = {
        pageNum: this.Page.pageNum,
        pageSize: this.Page.pageSize,
      }
      getMyDesiredList(params).then((res) => {
        if (res.code == 200) {
          this.list = res.data.records;
          this.Page.total = res.data.total
        }
      });
    },
    //获取需求待审核列表
    GetDesiredListPending() {
      const params = {
        pageNum: this.Page.pageNum,
        pageSize: this.Page.pageSize,
        state: Number(this.current),
        identity: this.roles == 'user' ? '0' : '1',
      }
      writerDesiredList(params).then((res) => {
        if (res.code == 200) {
          console.log(res, "res");
          this.list.push(...res.rows);
          this.Page.total += res.rows.total
        }
      })
    },
    GetOrderListByUserId() {
      const params = {
        pageNum: this.Page.pageNum,
        pageSize: this.Page.pageSize,
        state: Number(this.current),
        type: this.roles == 'user' ? '0' : '20',
      }
      getOrderListByUserId(params).then((res) => {
        if (res.code == 200) {
          this.list = res.data.records.map(el => {
            return {
              ...el.desired,
              allotPrice: el.allotPrice
            }
          });
        }
      })
    },
    //获取需求详情
    GetDesiredById(id) {
      const params = {
        desiredId: id,
      }
      getDesiredById(params).then((res) => {
        if (res.code == 200 && res.data) {
          res.data.price = res.data.price + ''
          // res.data.type = res.data.type + ''
          res.data.state = res.data.state + ''
          this.modal = true;
          this.title = "基础详情";
          // this.single = false
          if (res.data.type) {
            this.clickType = res.data.type.split(',')
          }
          if (res.data.order) {
            res.data.order.state = res.data.order.state + ''
          }
          this.date = [res.data.startTime, res.data.endTime]
          this.formValidate = res.data
          if (res.data.file) {
            this.defaultList = res.data.file.split(',').map(x => {
              return {
                name: this.getFileName(x),
                url: x,
              }
            })
          }
          if (this.formValidate.order.state >= 50) {
            this.GetOrderApportionByUserId()

          }
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    //获取需求详情
    GetDesiredInfo(id) {
      const params = {
        desiredId: id,
      }
      getDesiredInfo(params).then((res) => {
        if (res.code == 200 && res.data) {
          res.data.price = res.data.price + ''
          // res.data.type = res.data.type + ''
          res.data.state = res.data.state + ''
          this.modal = true;
          this.title = "基础详情";
          // this.single = false
          if (res.data.type) {
            this.clickType = res.data.type.split(',')
          }
          if (res.data.order) {
            res.data.order.state = res.data.order.state + ''
          }
          this.date = [res.data.startTime, res.data.endTime]
          this.formValidate = res.data
          if (res.data.file) {
            this.defaultList = res.data.file.split(',').map(x => {
              return {
                name: this.getFileName(x),
                url: x,
              }
            })
          }
          if (this.formValidate.order.state >= 50) {
            this.GetOrderApportionByUserId()

          }
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    //获取需求信息
    GetOrderRecords(id) {
      const params = {
        desiredId: id,
      }
      getOrderRecords(params).then((res) => {
        console.log(res, "res");
        if (res.code == 200) {
          if (res.data.length != 0) {
            this.TimelineArr = res.data.reverse()
            this.TimelineArr.forEach(item => {
              if (item.type == 5) {
                item.content = JSON.parse(item.content)
              }
            })
          }
        }
      })
    },
    GetOrderApportionByUserId() {
      const params = {
        desiredId: this.formValidate.id,
        identity: this.roles == 'user' ? '0' : '1',
      }
      getOrderApportionByUserId(params).then((res) => {
        if (res.code == 200) {
          if (res.data && res.data.feedbackFile) {
            this.feedbackList = res.data.feedbackFile.split(',').map(x => {
              return {
                name: this.getFileName(x),
                url: x,
              }
            })
          }
          this.feedbackFrom = res.data

        }
      })
    },
    //获取订单类型
    GetOrderTypeList() {
      getOrderTypeList().then(res => {
        this.type = res.data.map(x => {
          return {
            label: x.name,
            value: x.id + ''
          }
        })
      })
    },
    //日期选择
    handleClickDate(val) {
      console.log(val, "val");
      this.formValidate.startTime = val[0]
      this.formValidate.endTime = val[1]
    },
    //上传附件
    FileUploadInput(file) {
      console.log(file, "file");
      this.defaultList = []
      this.defaultList.push({
        name: this.getFileName(file),
        url: file
      })
    },
    FileUploadInput1(file) {
      console.log(file, "file");
      // this.feedbackFrom.feedbackFile = file
      this.feedbackList = []
      this.feedbackList.push({
        name: this.getFileName(file),
        url: file
      })
    },
    FileUploadInput2(file) {
      this.evaluationList = []
      console.log(file, "file");
      // this.feedbackFrom.feedbackFile = file
      this.evaluationList.push({
        name: this.getFileName(file),
        url: file
      })
    },
    //页面切换
    PageChange(e) {
      console.log(e, 'eeee');
      this.GetOrderList()
    },
    getClass(val) {
      if (!this.modal) return "";
      const currentState = this.formValidate.order ? this.formValidate.order.state : this.formValidate.state;
      return val == currentState ? "active" : val <= currentState ? "expired" : "";
    },
    getType(val) {
      if (!val) return '';
      return val.split(',')
        .map(x => {
          const found = this.type.find(y => y.value == x);
          return found ? found.label : '';
        })
        .join(',');
    },
    payment() {
      // console.log({ id: this.formValidate.id,title:this.formValidate.title },this.formValidate, "this.formValidate");
      if (this.formValidate && this.formValidate.order && this.formValidate.order.state != '70') {
        updateDesired({
          id: this.formValidate.id,
          title: this.formValidate.title,
          payRatio: this.paymentType == 0 ? '100' : this.formValidate.payRatio
        }).then(res => {
          if (res.code == 200) {
            this.$Message.success('付款成功!');
            this.QRCode = false
            this.modal = false
            this.GetOrderList()
          }
        })
      } else {
        payOrder(this.formValidate).then(res => {
          if (res.code == 200) {
            this.$Message.success('付款成功!');
            this.modal = false
            this.QRCode = false
            this.GetOrderList()
          }
        })
      }

    },
    clickTypeFun(val) {
      console.log(val, "val");
      this.formValidate.type = val.join(',')
    },
    //下载附件
    downloadLocalFile(file) {
      console.log(this.formValidate.file, "this.formValidate.file");
      let files = file.split(',')
      files.forEach(item => {
        window.open(this.baseUrl + item, '_blank')
      })

    },
    //下载附件
    downLoadFile(file) {
      window.open(this.baseUrl + file, '_blank')
    },
    // downloadLocalFile() {
    //   // 创建一个 <a> 标签
    //   const a = document.createElement('a');
    //   // 设置文件的下载地址，这里假设文件在 public 目录下
    //   a.href = '/static/example.pdf'; 
    //   // 设置下载的文件名
    //   a.download = 'example.pdf';
    //   // 模拟点击 <a> 标签触发下载
    //   a.click();
    //   // 移除 <a> 标签
    //   a.remove();
    // }
    //去审核
    ToReview(state) {
      this.feedbackFrom.state = state

      if (state == '65') {
        this.$Modal.confirm({
          title: '驳回原因:', // 添加标题
          render: (h) => {
            return h(Input, {
              props: {
                size: "large",
                value: this.feedbackFrom.remark,
                autofocus: true,
                placeholder: '请填写驳回原因'
              },
              on: {
                input: (event) => {
                  console.log(event);
                  this.feedbackFrom.remark = event
                }
              }
            })
          }, onOk: () => {
            auditOrderFeedback({
              ...this.feedbackFrom,
              orderId: this.formValidate.order.id,
            }).then(res => {
              if (res.code === 200) {
                this.cancel()
                this.GetOrderList();
              }
            });
          }
        })
        return
      } else {
        auditOrderFeedback({
          ...this.feedbackFrom,
          orderId: this.formValidate.order.id,
        }).then(res => {
          if (res.code == 200) {
            this.$Message.success('操作成功!');
            this.upLoadBackFile = false
            this.modal = false
            this.GetOrderList()
          }
        })
      }
      // console.log(this.feedbackFrom, "this.feedbackFrom");

    },
    //去评价
    evaluationFun() {
      // if (!this.evaluationModel.star) {
      //   this.$Message.error('请选择星级!');
      //   return
      // }
      this.evaluationModel.image = this.evaluationList.map(x => x.url).join(',')
      saveEvaluate({
        ...this.evaluationModel,
        orderId: this.formValidate.id
      }).then(res => {
        if (res.code == 200) {
          this.$Message.success('操作成功!');
          this.evaluation = false
          this.modal = false
          setTimeout(() => {
            this.evaluationModel = {
              image: [],
              // star: 0,
              content: ''
            }
          }, 1000);

        }
      })
    },
    //去售后
    GetorderAfterSale() {
      orderAfterSale({
        orderId: this.formValidate.order.id,
        // id: this.formValidate.id,
      }).then(res => {
        if (res.code == 200) {
          this.$Message.success('已向客服提交售后申请，等待客服审核!');
          this.GetOrderList()
        }
      })
    },
    //已完成
    toCompleted() {
      completeOrder({
        orderId: this.formValidate.id,
        desiredId: this.formValidate.order.id
      }).then(res => {
        if (res.code == 200) {
          this.$Message.success('操作成功，该订单已完成!');
          this.modal = false
          this.GetOrderList()
        }
      })
    },
    getCurrent(item) {
      if (!(item && item.order)) return
      for (let i = 0; i < this.typeList1.length; i++) {
        const [min, max] = this.typeList1[i].range;
        if (item.order.state >= min && item.order.state <= max) {
          return i;
        }
      }
      // return -1;
    },
    getFileList(file) {
      // 检查 formValidate.file 是否为字符串
      if (typeof file === 'string') {
        return file.split(',');
      }
      return [];
    },
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
  },
};
</script>

<style scoped lang="scss">
.wrapper {
  margin-bottom: 40px;
}

.box {
  overflow: hidden;
}

.page-size {
  margin: 15px 0px;
  text-align: right;
}

/** 订单列表 */
.order-list {
  border: 1px solid #ddd;
  border-radius: 3px;
  margin-bottom: 10px;

  &:hover {
    .del-btn {
      visibility: visible;
    }
  }

  .del-btn {
    visibility: hidden;
  }

  .order-header {
    display: flex;
    align-items: center;
    padding: 10px;
    justify-content: space-between;
    border-bottom: 1px solid #ddd;

    >div:nth-child(1)>div:nth-child(2) {
      font-size: 12px;
      color: #999;
      margin-top: 3px;
    }
  }

  .order-body {
    display: flex;
    justify-content: space-between;
    color: #999;
    padding: 10px;

    .goods-list>div {
      width: 500px;
      display: flex;
      margin-bottom: 10px;

      img {
        width: 60px;
        height: 60px;
        margin-right: 10px;
      }

      >div {
        flex: 1;
      }
    }

    >div:nth-child(2) {
      width: 150px;
      text-align: center;

      span {
        color: #438cde;
        cursor: pointer;

        &:hover {
          color: $theme_color;
        }
      }

      .ivu-icon {
        color: #ff8f23;
        cursor: pointer;

        &:hover {
          color: $theme_color;
        }
      }
    }

    >div:nth-child(3) {
      width: 100px;

      .ivu-btn {
        margin-bottom: 10px;
      }
    }
  }
}

.only-goods-list {
  // display: flex;
  // flex-wrap: wrap;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.only-goods-list-item {
  // padding-top: 30px;
  width: 287px;
  height: 245px;
  border-radius: 9.8px;
  opacity: 1;
  margin-bottom: 14.3px;
  cursor: pointer;
  background: #ffffff70;
  transition: all 0.4s ease;
  box-shadow: 0px 1px 13px 0px #e5e5e5;
  position: relative;
  display: flex;
  flex-direction: column;
  // align-items: center;
  overflow: hidden;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0px 1px 14px 0px #c5c5c5;

    >.white-shadow {
      opacity: 1;
    }

    >.goods-img {
      >img {
        opacity: 0.85 !important;
        object-fit: cover;

      }
    }
  }
}

.goods-img {
  margin-bottom: 9.8px;
  text-align: center;
  // padding: 0 10px;
  width: 100%;

  >img {
    transition: all 0.4s ease;
    width: auto;
    max-height: 183px;

  }
}

.goods-name {
  font-size: 18px;

  font-weight: 600;
  line-height: 22px;
  // text-align: center;
  letter-spacing: 0px;
  width: 200px;
  // margin: 0 auto 12.4px auto;
  padding: 0 10px;
  color: #333333;
  // -webkit-text-stroke: #979797 0.7px;
  /* 浏览器可能不支持 */
}

.goods-desc {
  font-size: 16px;
  font-weight: normal;
  line-height: 17px;
  padding: 10px 10px 0;
  // text-align: center;
  letter-spacing: 0px;
  color: #666666;

  -webkit-text-stroke: #979797 0.7px;
  /* 浏览器可能不支持 */
}

.goods-desc1 {
  font-size: 14px;
  font-weight: normal;
  line-height: 17px;
  padding: 10px 10px 15px;
  // text-align: center;
  letter-spacing: 0px;
  color: #555454;

  -webkit-text-stroke: #666 0.7px;
  /* 浏览器可能不支持 */
}

.goods-price {
  font-weight: normal;
  line-height: 30px;
  padding: 10px;
  // text-align: center;
  letter-spacing: 0px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .price {
    font-size: 25.2px;
    color: #f31947;
    -webkit-text-stroke: #979797 0.7px;
    /* 浏览器可能不支持 */
  }

  .state {
    font-size: 16.2px;
  }

}

.white-shadow {
  width: 287px;
  height: 122px;
  border-radius: 0px 0px 10px 10px;
  opacity: 1;
  position: absolute;
  bottom: 0;
  left: 0;
  opacity: 0;
  display: flex;
  justify-content: center;
  transition: 0.35s;
  align-items: center;
  background: linear-gradient(180deg,
      rgba(252, 252, 252, 0.58) -50%,
      #ffffff 99%);
}

.search {
  width: 143px;
  height: 45px;
  border-radius: 22.5px;
  opacity: 1;
  font-size: 20px;
  font-weight: normal;
  text-align: center;
  letter-spacing: 0px;
  line-height: 45px;
  color: #ffffff;
  background: $theme_color;
}

.QRCode {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;

  .QRImg {
    width: 150px;
    height: 150px;
    border: #333333 1px solid;
    border-radius: 5px;
    margin-bottom: 15px;
  }
}

.QRflex {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

::v-deep .ivu-modal-wrap1 .ivu-modal {
  top: calc(50% - 150px) !important;
}
</style>
